import React,{Component} from 'react'
import PubSub from 'pubsub-js'
import Axios from 'axios/dist/axios'

export default class BoxList extends Component{

    constructor() {
        super()
        this.state = {
            initView: true,
            loading: false,
            err: null,
            user: []
        }
        // 订阅消息
        var token = PubSub.subscribe('search', (msg,keyword) => {
            this.loadData(keyword)
        });
    }

    loadData = (keyword) =>{
        this.setState({
            initView: false,
            loading: true,
            err: null,
        })
        Axios.get("https://api.github.com/search/repositories?sort=stars&order=desc&q="+keyword)
            .then(resp => {
                console.log(resp)
                this.setState({
                    initView: false,
                    loading: false,
                    err: null,
                    user: resp.data.items
                })
            })
            .catch(err => {
                this.setState({
                initView: false,
                loading: false,
                err:'请求失败'
            })})
    }

    render(){
        if(this.state.initView) return <h2>请输入你喜欢的的技术,例如 python</h2>
        if(this.state.loading) return <h2>正在搜索中...</h2>
        if(this.state.err != null) return <h2>错误: {this.state.err}</h2>

        return (
            <div className="row">
                {this.state.user.map(item => (
                    <div className="col-md-3">
                        <div className="panel panel-default">
                            <div className="panel-body">
                            <img src={item.owner.avatar_url} alt="" className="img-responsive center-block img-circle"/><br/>
                             用户:<a href={item.owner.html_url}>{item.owner.login}</a>
                            </div>
                            <div className="panel-footer">代表作: 
                            <a href={item.html_url}>{item.name}</a>
                            <span style={{float:'right'}}>
                                <span class="glyphicon glyphicon-star" aria-hidden="true"></span> {item.stargazers_count}
                            </span>
                            </div>
                        </div>
                    </div>
                ))}
                
            </div>
        )
    }
}